import fs from 'fs-extra';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 获取模板目录路径
export const getTemplateDir = (...paths) => 
  path.resolve(__dirname, 'template', ...paths);

// 检查目录是否为空
export const isEmpty = (path) => {
  const files = fs.readdirSync(path);
  return files.length === 0 || (files.length === 1 && files[0] === '.git');
};

// 清空目录
export const emptyDir = (dir) => {
  if (!fs.existsSync(dir)) return;
  
  for (const file of fs.readdirSync(dir)) {
    if (file === '.git') continue;
    fs.rmSync(path.resolve(dir, file), { recursive: true, force: true });
  }
};

// 复制模板文件
export const copyTemplate = (src, dest, context = {}) => {
  const stats = fs.statSync(src);

  if (stats.isDirectory()) {
    fs.mkdirSync(dest, { recursive: true });
    for (const file of fs.readdirSync(src)) {
      copyTemplate(path.resolve(src, file), path.resolve(dest, file), context);
    }
    return;
  }

  const filename = path.basename(src);
  
  // 跳过不需要处理的文件
  if (filename.startsWith('_') || filename === 'package.json') {
    return;
  }

  // 处理模板文件
  if (filename.endsWith('.template')) {
    const content = fs.readFileSync(src, 'utf-8');
    const resolvedContent = Object.entries(context).reduce(
      (content, [key, value]) => content.replace(new RegExp(`{{ ${key} }}`, 'g'), value),
      content
    );
    fs.writeFileSync(dest.replace(/\.template$/, ''), resolvedContent);
    return;
  }

  fs.copyFileSync(src, dest);
};